<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog
    :title="!form.id ? '新增': '修改'"
    :visible.sync="visible"
    :close-on-click-modal=false
    v-dialogDrag
    append-to-body>
    <el-form ref="dataForm" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品类型" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="menuOptions"
              :disabled="form.workPositionType === '0'"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="选择上级产品类型"
              noOptionsText="暂无数据"
              @input="handleParentIdChange"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  label="类别" prop="workPositionType">
            <el-radio-group v-model="form.workPositionType" :disabled="flg" @change="updateRules">
              <el-radio-button label="0">产品类型</el-radio-button>
              <el-radio-button label="1">工位</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入工位/产品类型名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品号" prop="itemCode">
            <avue-select
              v-model="form.itemCode"
              :dic="itemCodeList"
              :disabled="form.workPositionType !== '0'"
              :props="{label: 'label',value: 'value'}"
              clearable
              dialog-width="100%"
              filterable
              placeholder="请选择品号"
              style="width:200px;margin-right: 5px"></avue-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="工位顺序" prop="sortOrder" v-if="form.workPositionType === '1'">
        <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fetchMenuTree, addObj, putObj ,getObj} from '@/api/pfoc/workposition'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {getItemCodeList} from "@/api/workorder/workordercps";

export default {
  name: 'workPositionForm',
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 菜单树选项
      menuOptions: [],
      // 是否显示弹出层
      visible: false,
      // 查询参数
      queryParams: {
        workPositionType: "0",
      },
      form: {
        id: undefined,//工位ID
        itemCode:null,//品号
        parentId: undefined,//父级ID
        name: null,//工位类名称
        workPositionType: null,//类别
        workPositionName: null,//工位名
        sortOrder: undefined,//工位顺序
      },
      itemCodeList: [], //品号集合
      flg:false,//是否可选工位类别
      // 表单校验
      rules: {
        name: [
          {required: true, message: '工位/产品类型名称不能为空', trigger: 'blur'}
        ],
        workPositionType:[
          {required: true, message: '请选择添加的类别', trigger: 'blur'}
        ],
        sortOrder: [
          {required: true, message: '工位顺序不能为空', trigger: 'blur'}
        ],
        parentId: [],
        itemCode:[]
      }
    }
  },
  watch: {
    'form.parentId': function(newVal, oldVal) {
      // 判断当前是否是作业新增
      if(this.form.workPositionType === '1' && this.validatenull(this.form.id)){
        //parentId不为-1且不为undefined，则表示当前是作业新增，需要判断是否为顶级节点，顶级节点需要设置parentId为-1
        if(this.form.parentId !== -1 && this.form.parentId  !== undefined){
          //获取当前选中节点下有多少数据
          this.form.sortOrder = this.countLeaves(this.menuOptions, this.form.parentId)+1;
        }
      }
      if(!this.validatenull(this.form.workPositionType)){
        this.$nextTick(() => {
          if(!this.validatenull(this.findNodeById(this.menuOptions[0].children,newVal))){
            this.form.itemCode = this.findNodeById(this.menuOptions[0].children,newVal).itemCode
          }
        })
      }

    }
  },
  created() {
    this.getItemCodeListData();
  },
  methods: {
    init(isEdit, id , workPositionType) {
      this.visible = true
      this.getTreeselect()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.form.sortOrder = undefined
        this.form.parentId = id
        this.form.workPositionType = workPositionType
        this.flg = !this.validatenull(workPositionType) && !this.validatenull(id);
        if (isEdit) {
          getObj(id).then(response => {
            this.form = Object.assign({}, this.form, Object.fromEntries(
              Object.entries(response.data.data).filter(([key]) => key in this.form)
            ));//防止为form新增属性，如createTime等，此方法只给form中存在的属性赋值
            if(this.form.workPositionType==='1'){
              this.form.name = this.form.workPositionName;
            }
          })
        } else {
          this.form.id = undefined
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.validatenull(this.form.parentId)) {
            this.form.parentId = -1
          }
          if(this.form.workPositionType === '1'){
            this.form.workPositionName = this.form.name;
            const selectedItem = this.findNodeById(this.menuOptions[0].children,this.form.parentId)
            this.form.name = selectedItem.label;
          }else{
            this.form.workPositionName =null;
          }
          if (this.form.id) {
            putObj(this.form).then(data => {
              this.$message.success('修改成功')
              this.visible = false
              this.$emit('refreshDataList')
            })
          } else {
            addObj(this.form).then(data => {
              this.$message.success('添加成功')
              this.visible = false
              this.$emit('refreshDataList')
            })
          }
        }
      })
    },
    /**获取品号*/
    getItemCodeListData() {
      getItemCodeList().then(response => {
        this.itemCodeList = response.data.data
      })
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      //创建对象
      fetchMenuTree().then(response => {
        this.menuOptions = []
        const menu = {id: -1, name: '根', children: []}
        menu.children = response.data.data
        this.menuOptions.push(menu)
        // 判断当前是否是作业新增
        if(this.form.workPositionType === '1' && this.validatenull(this.form.id)){
          //parentId不为-1且不为undefined，则表示当前是作业新增，需要判断是否为顶级节点，顶级节点需要设置parentId为-1
          if(this.form.parentId !== -1 && this.form.parentId  !== undefined){
            //获取当前选中节点下有多少数据
            this.form.sortOrder = this.countLeaves(this.menuOptions, this.form.parentId)+1;
          }
        }
      })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      if(node.workPositionType==='1'){
        return {
          id: node.id,
          label: null,
          itemCode: node.itemCode,
          children: node.children
        }
      }else {
        return {
          id: node.id,
          label: node.name,
          itemCode: node.itemCode,
          children: node.children
        }
      }
    },
    /** 动态更新表单校验规则 */
    updateRules() {
      if (this.form.workPositionType === '1') {
        this.form.parentId = undefined;
        this.rules.parentId = [
          { validator: this.validateParentId, trigger: 'blur' }
        ]
      } else {
        this.rules.parentId = []
        this.form.sortOrder = undefined;
        this.form.parentId = -1;
        this.form.itemCode = null;
        this.rules.itemCode = [
          { required: true, message: '品号不能为空', trigger: 'blur' }
        ]
      }
      this.$refs['dataForm'].clearValidate('parentId')
    },
    /** 自定义校验规则 */
    validateParentId(rule, value, callback) {
      if (this.form.workPositionType === '1' && (this.form.parentId === undefined || this.form.parentId === -1)) {
        callback(new Error('请选择有效的上级工位类型'))
      } else {
        callback()
      }
    },
    /** 在选择完符合产品类别的数据时重新校验 parentId */
    handleParentIdChange(value) {
      if (this.form.parentId !== undefined && this.form.parentId !== -1) {
        this.$refs['dataForm'].clearValidate('parentId')
      } else {
        this.$refs['dataForm'].validateField('parentId')
      }
    },
    //递归函数
    findNodeById(tree, id) {
      for (let node of tree) {
        if (node.id === id) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const foundNode = this.findNodeById(node.children, id);
          if (foundNode) {
            return foundNode;
          }
        }
      }
      return null;
    },
    // 获取当前选中节点下有多少数据
    countLeaves(options, selectedId) {
      let count = 0;
      function traverse(nodes) {
        nodes.forEach(node => {
          if (node.id === selectedId) {
            if (node.children) {
              node.children.forEach(child => {
                if (!child.children) {
                  count++;
                }
              });
            }
          } else if (node.children) {
            traverse(node.children);
          }
        });
      }
      traverse(options);
      return count;
    },

  }
}
</script>
